﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Editor.Utilities;

namespace Editor
{
    public partial class CreateForm : Form, IDictSubject<string>
    {
        private int previouslySelectedIndex = 0;

        public CreateForm()
        {
            InitializeComponent();
        }

        public CreateForm(string title)
            : this()
        {
            this.Text = title; 
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (textBoxName.Text.Trim() == string.Empty)
            {
                MessageBox.Show("İsim girmelisiniz!", "Hata!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                DialogResult = System.Windows.Forms.DialogResult.Retry;
            }
            else
            {
                Dictionary[EditorForm.SupportedLanguages[previouslySelectedIndex]] = 
                    textBoxName.Text;
                DialogResult = System.Windows.Forms.DialogResult.OK;
            }
        }

        private void CreateForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (DialogResult == System.Windows.Forms.DialogResult.Retry)
                e.Cancel = true;
        }

        private void textBox1_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                button1_Click(sender, new EventArgs());
        }

        private void resetSubject()
        {
            previouslySelectedIndex = EditorForm.CurrentLanguageIndex;
        }

        private T changeSubject<T>(string lang, int newIndex, T subject, ref SDictionary<T> dict)
        {
            dict[EditorForm.SupportedLanguages[previouslySelectedIndex]] =
                subject;

            T result;

            if (dict.ContainsLanguage(lang))
                result = dict[lang];
            else
                result = default(T);

            previouslySelectedIndex = newIndex;

            return result;
        }

        private void CreateForm_Load(object sender, EventArgs e)
        {
            Dictionary = new SDictionary<string>();
            comboBoxLanguage.Items.AddRange(EditorForm.SupportedLanguages);
            comboBoxLanguage.SelectedIndex = EditorForm.CurrentLanguageIndex;
        }

        public SDictionary<string> Dictionary { get; set; }

        private void comboBoxLanguage_SelectedIndexChanged(object sender, EventArgs e)
        {
            SDictionary<string> dict = Dictionary;
            textBoxName.Text = changeSubject(comboBoxLanguage.SelectedItem as string,
                comboBoxLanguage.SelectedIndex, textBoxName.Text, ref dict);
            Dictionary = dict;
        }
    }
}
